package com.example.doctor.config.executor;

import com.example.doctor.config.ThreadParameter;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author rlj
 * @Date 2021/4/7 17:38
 * @Version 1.0
 */
@Component
public class MyThreadConfig {

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadParameter threadParameter){
        // 获得当前cpu 核心
        int i = Runtime.getRuntime().availableProcessors();

        if (ObjectUtils.isEmpty(threadParameter.getCoreSize())){
            threadParameter.setCoreSize(3);
        }
        if (ObjectUtils.isEmpty(threadParameter.getMaxSize())){
            threadParameter.setMaxSize(i += 1);
        }
        if (ObjectUtils.isEmpty(threadParameter.getKeepAliveTime())){
            threadParameter.setKeepAliveTime(3L);
        }

        return new ThreadPoolExecutor(
                threadParameter.getCoreSize(),
                threadParameter.getMaxSize(),
                threadParameter.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
